package cn.tedu.ivosback.dictoption.service.impl;

import cn.tedu.ivosback.base.exception.ServiceException;
import cn.tedu.ivosback.base.response.StatusCode;
import cn.tedu.ivosback.dict.mapper.DictMapper;
import cn.tedu.ivosback.dict.pojo.dto.DictQuery;
import cn.tedu.ivosback.dict.pojo.vo.DictVO;
import cn.tedu.ivosback.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivosback.dictoption.pojo.dto.DictOptionParam;
import cn.tedu.ivosback.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivosback.dictoption.pojo.entity.DictOption;
import cn.tedu.ivosback.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivosback.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;

    @Override
    public List<DictOptionVO> selectDictOption(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典项列表:dictOptionQuery={}", dictOptionQuery);
        return dictOptionMapper.selectDictOption(dictOptionQuery);
    }

    @Override
    public void saveDictOption(DictOptionParam dictOptionParam) {
        log.debug("保存字典项:dictOptionParam={}", dictOptionParam);
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionParam, dictOption);
        if (dictOptionParam.getId() == null) {
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insertDictOption(dictOption);
        } else {
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.updateDictOption(dictOption);
        }
    }

    @Override
    public void deleteDictOption(Long id) {
        log.debug("删除字典项:id={}", id);
        dictOptionMapper.deleteDictOption(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("根据字典编码查询字典项列表:code={}", code);
        DictQuery dictQuery = new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> list = dictMapper.selectDict(dictQuery);
        if (list.size() > 0 && list != null) {
            DictVO dictVO = list.get(0);
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            return dictOptionMapper.selectDictOption(dictOptionQuery);
        } else {
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }
}
